package org.ezplatform.goa.document.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.cache.api.system.user.UserCacheCo;
import org.ezplatform.cache.api.system.user.UserCacheManager;
import org.ezplatform.cloud.api.bpm.BpmApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.cloud.common.condition.AppAuthCondition;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.annotation.AppAuth;
import org.ezplatform.core.annotation.AppLog;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.goa.document.cache.GovCacheManager;
import org.ezplatform.goa.document.constant.LogConstant;
import org.ezplatform.goa.document.constant.RightConstant;
import org.ezplatform.goa.document.dao.GoaReceiveOrgDao;
import org.ezplatform.goa.document.dao.GovDocAttachmentDao;
import org.ezplatform.goa.document.dao.GovSendFileDao;
import org.ezplatform.goa.document.entity.*;
import org.ezplatform.goa.document.service.*;
import org.ezplatform.goa.document.util.DocumentSecUtils;
import org.ezplatform.goa.document.util.DocumentValidateUtil;
import org.ezplatform.goa.document.util.ParamEscapeUtil;
import org.ezplatform.office.api.client.oa.approve.ApproveApiService;
import org.ezplatform.sdk.AccessToken;
import org.ezplatform.sdk.Client;

import org.ezplatform.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 按钮功能后台--
 * 流程列表/
 * @author 47520
 *
 */
@Controller
@RequestMapping(value = "/api/w/goa/document/govFlowListController")
@Conditional(AppAuthCondition.class)
@AppAuth(identifier = "goa_document")
public class GovFlowListWebApiController extends BaseController<GovSendFile,String>{
	private final Logger logger = LoggerFactory.getLogger(GovFlowListWebApiController.class);
	@Autowired
	private GovSendFileService sendFileService;
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private RestClient restClient;
	
	@Autowired
	private GovCommonService  govCommonService;
	@Autowired
    private LogService logService;
	
	@Autowired
	private GovFlowTaskService govFlowTaskService;
	
/*	@Autowired
	private GovBpmFollowService govBpmFollowService;
	
	@Autowired
	private GovMyAttentionService  myAttentionService;*/

	@Autowired
	private GovCacheManager govCacheManager;

	@Autowired
	private GovBaseSetService govBaseSetService;
	
	@Autowired
	private GovBaseSetService baseSetService;
	
	@Autowired
	private GovSendFileDao govSendFileDao;
	
	@Autowired
	private SignQueryService signQueryService;
	
	@Autowired
    private GovDistributeUserService govDistributeUserService;
	
	@Autowired
	private GovDocReceiveFileService govDocReceiveFileService;
	
	@Autowired
	private DownloadFilesService downloadFilesService;
	
	@Autowired
	private GovDistributeRecordService govDistributeRecordService;
	
	@Autowired
	private GovDocAttachmentDao govDocAttachmentDao;

    @Autowired
    private BpmApiService bpmApiService;

    @Autowired
    private ApproveApiService approveApiService;

	@Autowired
	private GoaReceiveOrgDao goaReceiveOrgDao;

	@Autowired
	private UserCacheManager userCacheManager;

	
	@Override
	protected BaseService<GovSendFile, String> getEntityService() {
		// TODO Auto-generated method stub
		return null;
	}


	/**
	 * 获取待办列表
	 * @name: getUndoList
	 * @param request
	 * @param module 模块编码
	 * @param category 流程类型
	 * @param model
	 * @return: java.lang.String
	 * @date: 2022/10/18 14:05
	 *
	*/
    @RequestMapping({ "/getUndoList" })
    @ResponseBody
    @AppLog
    public String getUndoList(HttpServletRequest request,String module,String category, Model model) {
    	WebUser webUser = WebUtils.getCurrentUser();
    	Map<String, String> map = new HashMap<String, String>();
    	List<String> businessKeyList =  new ArrayList<String>();
		if(!DocumentValidateUtil.validateParamsString(module,category)) {
			throw new ValidationException("非法参数");
		}
		if (StringUtils.isNotBlank(category)) {
            String token = webUser.getJwtToken();
			map.put("module", module);
			map.put("category", category);
            map.put("userId",webUser.getUserId());
            map.put("corpId",webUser.getCorpId());
            map.put("token",token);
            map.put("orgId",webUser.getOrgId());
			String result = approveApiService.pendingTaskList(map,token);
			if (StringUtils.isNoneBlank(result)) {
				JSONObject json = (JSONObject) JSONObject.parse(result);
				Object content = json.get("content");
				if (content != null) {
					JSONArray val = (JSONArray)content;
					if (val.size() > 0) {
						for (int i = 0; i < val.size(); i++) {
							if (val.getJSONObject(i) != null) {
								String businessKey = (String) val.getJSONObject(i).get("businessKey");
								businessKeyList.add(businessKey);
							}
						}
					}
					if (!businessKeyList.isEmpty()) {
						List<Map<String, Object>> collectionList = govCommonService.getBusinsessList(businessKeyList);
						if (collectionList != null && !collectionList.isEmpty()) {
							for (int i = 0; i < val.size(); i++) {
								for (int j = 0; j < collectionList.size(); j++) {
									if (collectionList.get(j).get("id") !=null) {
										if (collectionList.get(j).get("id").toString().equals(val.getJSONObject(i).get("businessKey"))) {
											val.getJSONObject(i).put("emergency_degree", collectionList.get(j).get("emergency_degree"));
											break;
										}
									}
								}
							}
							json.put("content", val);
							return json.toJSONString();
						}
					}
				}
			}
			
		}
    	
    	return null;
    }
	
    
    /**
     * 获取紧急程度数据
     * @name: getEmergency
     * @param request
     * @param id 公文数据id
     * @param model
     * @return: org.ezplatform.core.web.view.OperationResult
     * @date: 2022/10/18 14:14
     *
    */
    @RequestMapping({ "/getEmergency" })
    @ResponseBody
    @AppLog
    public OperationResult getEmergency(HttpServletRequest request,String id, Model model) {
    	if (StringUtils.isNotEmpty(id)) {
			if(!DocumentValidateUtil.validateParamsString(id)) {
				throw new ValidationException("非法参数");
			}
			Map<String, Object> emergency = govCommonService.getEmergency(id);
			return OperationResult.buildSuccessResult("获取成功", emergency);
		}
    	return OperationResult.buildFailureResult("获取失败");
    }
    
    
   /**
    * 获取收藏数据
    * @name: getCollection
    * @param request
    * @param id  公文数据id
    * @return: org.ezplatform.core.web.view.OperationResult
    * @date: 2022/10/18 14:15
    *
   */
	@RequestMapping({ "/getCollection" })
	@ResponseBody
	@AppLog
	public OperationResult getCollection(HttpServletRequest request,String id) {
		WebUser webUser = WebUtils.getCurrentUser();
		if (StringUtils.isNotEmpty(id)) {
			if(!DocumentValidateUtil.validateParamsString(id)) {
				throw new ValidationException("非法参数");
			}
			List<String> collection = govCommonService.getCollection(id, webUser.getUserId(),"2");	
			return OperationResult.buildSuccessResult("获取成功", collection);
		}
		return OperationResult.buildFailureResult("获取失败");
	}
 
	/**
	 * 是否存在附件
	 * @name: hasAttachment
	 * @param request
	 * @param id 公文数据id
	 * @return: org.ezplatform.core.web.view.OperationResult
	 * @date: 2022/10/18 14:15
	 *
	*/
	@RequestMapping({ "/hasAttachment" })
	@ResponseBody
	@AppLog
	public OperationResult hasAttachment(HttpServletRequest request,String id) {
		WebUser webUser = WebUtils.getCurrentUser();
		if (StringUtils.isNotEmpty(id)) {
			if(!DocumentValidateUtil.validateParamsString(id)) {
				throw new ValidationException("非法参数");
			}
			List<String> list =new ArrayList<String>();
			list.add(id);
			List<String> collection = govCommonService.getAttachList(list, webUser.getUserId());	
			return OperationResult.buildSuccessResult("获取成功", collection);
		}
		return OperationResult.buildFailureResult("获取失败");
	}
	
	/**
	 * 草稿箱删除
	 * @Title: draftFlowDelete   
	 * @param module 模块编码
	 * @param permissionCode 权限编码
	 * @param ids 公文数据id
	 * @author xuwl
	 * @date 2019-12-18 1:39:30 PM
	 */
	@RequestMapping(value = "/draftFlowDelete")
	@ResponseBody
	public OperationResult draftFlowDelete(String module, String permissionCode, @RequestParam("ids") String[] ids,@RequestParam("secdatacode") String[] secdatacode) {
		logger.info("========draftFlowDelete====start===");
		WebUser user = WebUtils.getCurrentUser();
		if(!DocumentValidateUtil.validateParamsString(module,permissionCode)) {
			throw new ValidationException("非法参数");
		}
		Map userParams = new HashMap();
		userParams.put("userId", user.getUserId());
		userParams.put("corpId", user.getCorpId());
		String taskIds = "";
		String json = "";
		if ((null != ids) && (ids.length > 0)) {
			for (int i = 0; i < ids.length; i++) {
				taskIds = taskIds + "," + ids[i];
				if(!DocumentValidateUtil.validateParamsString(ids[i])) {
					throw new ValidationException("非法参数");
				}
				if(!DocumentValidateUtil.validateParamSecdatacode(secdatacode[i])) {
					throw new ValidationException("非法参数");
				}
			}
			userParams.put("taskIds", taskIds.substring(1));
			List<String> idsList = Arrays.asList(ids);
			Map<String, String> proInsIdByTaskIds = govCommonService.getProInsIdByTaskIds(idsList);
			String proIds = proInsIdByTaskIds.get("returnIds");
			String businessKey = proInsIdByTaskIds.get("returnBusinessKey");
			if (StringUtils.isNotEmpty(proIds) && StringUtils.isNotEmpty(businessKey)) {
				//占时只处理单个删除
				if(ids.length==1){
					boolean checkData =false;
					if(StringUtils.isNotEmpty(secdatacode[0])){
						checkData = DealFieldEncodeUtils.checkData("processInstanceId" +proIds, "processflow", secdatacode[0]);
					}
					if(!checkData){
						return  OperationResult.buildFailureResult("数据错误，请重新操作");
					}

				}
				String[] dataIds = businessKey.split(",");
				govCommonService.getBizInfoById(dataIds, user.getJwtToken());
				Map params = new HashMap();
				params.put("userId", user.getUserId());
				params.put("corpId", user.getCorpId());
				params.put("type", "1");
				params.put("processInstanceIds", proIds);
				String content = "草稿箱";
				String[] idss = proIds.split(",");
				if (idss.length > 0) {
					String title = "";
					for (String id : idss) {
						title += govCommonService.getTitleByProInsId(id) + ",";
					}
					if (!"".equals(title)) {
						title = title.substring(0, title.length() - 1);
					}
					if (idss.length > 1) {
						content += "批量删除:" + title;
					} else {
						content += "删除:" + title;
					}
				}
				deleteFileNoByGovId(idss);
				bpmApiService.releaseProcessForm(params,user.getJwtToken());
				json = bpmApiService.deleteDraft(userParams,user.getJwtToken());
				if (logService.checkOptLog("0", "goa_document:draft:04", user.getJwtToken())) {
					logService.saveModuleLog("goa_document:draft:04", content, "");
				}
				return govCommonService.stringToOperation(json.replace("成功", "删除成功"));
			}else {
				return OperationResult.buildFailureResult("参数错误，请重新操作");
			}
		}
		return govCommonService.stringToOperation(json.replace("成功", "删除成功"));

	}
	
	/**
	 * 删除文号
	 * @param proIds
	 */
	private void deleteFileNoByGovId(String[] proIds) {
		String id = "";
		//ids为 procinstanti的集合
		try{
			for (int i = 0; i < proIds.length; i++) {
				//GovSendFile findOne = sendFileService.findOne(id);
				List<Map>  list = sendFileService.getSendFileInfoByProcId(proIds[i]);
				logger.error("======文号数据===="+ JSON.toJSONString(list));
				//查询是不是发文的流程
				if(CollectionUtils.isNotEmpty(list) && list.get(0)!=null) {
					Map  map = list.get(0);
					Integer a  = govSendFileDao.deleteSaveFileNo(map.get("file_no_see")+"");
					// 更新goa_doc_send_reserve_fileno状态
					String str = (String)map.get("issued_number");
					String newwh = "";
					String newStr = "";
					String jgdz = "";
					String nf  = "";
					String hm = "";
					//机关带子，年份，号码
					if(StringUtils.isNotBlank(str)){
						if(str.indexOf("]")>-1){//不显示文号名
							newStr = str.split("]")[1];
							jgdz = str.split("]")[0].replace("[","");
							if(newStr.indexOf('-')>-1){//不显示年份
								nf = newStr.split("-")[1];
								hm=	newStr.split("-")[2];
								if (hm.indexOf("|") > -1) {
									hm=	hm.split("\\|")[1];
								}
							}else {
								hm = newStr.split("〕")[1];
								if (hm.indexOf("|") > -1) {
									hm=	hm.split("\\|")[1];
								}
								nf=	newStr.split("〕")[0].split("〔")[1];
							}
						}else if(str.indexOf(')')>-1){//显示文号名
							jgdz = str.split("\\)")[0].replace("(","");
							newStr = str.split("\\)")[1];
							if(newStr.indexOf('-')>-1){//不显示年份
								nf = newStr.split("-")[1];
								hm=	newStr.split("-")[2];
								if (hm.indexOf("|") > -1) {
									hm=	hm.split("\\|")[1];
								}
							}else {
								if(newStr.indexOf("〕")>-1){
									String[] hmArr = newStr.split("〕");
									if(hmArr.length>1){
										hm = newStr.split("〕")[1];
									}
									String aa = newStr.split("〕")[0];
									if(aa.indexOf("〔")>-1){
										nf=	aa.split("〔")[1];
									}
								}
								if (hm.indexOf("|") > -1) {
									hm=	hm.split("\\|")[1];
								}
							}
						}else{
							newStr = str;
						}
					}
					newwh = jgdz+"〔"+nf+"〕"+hm;
					govSendFileDao.deleteReserveFileNo(newwh);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}

	}

	
	/**
	 * 获取待办列表数据
	 * @Description: 获取待办列表数据
	 * @Title: GovFlowListWebApiController 
	 * @author: Fangsx
	 * @Date: 2019年12月26日 下午2:53:35 
	 * @param start 开始页
	 * @param limit 页条目
	 * @param code 编码
	 * @param categoryCode 流程类型编码
	 * @param processName 流程名称
	 * @param preciseProcessName 流程名称
	 * @param title 标题
	 * @param startGroupName 发起单位
	 * @param startTimeBegin 发起时间 开始
	 * @param startTimeEnd 发起时间 结束
	 * @param receiveTimeBegin 接收时间 开始
	 * @param receiveTimeEnd 接收时间 结束
	 * @param createTimeBegin 创建时间 开始
	 * @param createTimeEnd 创建时间 结束
	 * @param from 来源
	 * @param orderby 排序
	 * @param order 排序
	 * @param status  流程状态  11-退回   12-转交
	 * @param isDeal 0 待办  1 待处理
	 * @param buttonGroup 活动权限分类
	 * @return
	 * @throws
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = { "/pendingTaskList" }, method = { RequestMethod.GET })
	@ResponseBody
	public Page pendingTaskList(HttpServletRequest request) {
		Long startTime = System.currentTimeMillis();
		WebUser user = WebUtils.getCurrentUser();
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		String index = ValidateUtils.filter(request.getParameter("start"));
		String limit = ValidateUtils.filter(request.getParameter("limit"));
		String page = ValidateUtils.filter(request.getParameter("page"));
		String rows = ValidateUtils.filter(request.getParameter("rows"));
		String code = ValidateUtils.filter(request.getParameter("code"));
		String category = ValidateUtils.filter(request.getParameter("categoryCode"));
		String processName = ValidateUtils.filter(request.getParameter("processName"));
		String preciseProcessName = StringUtils.null2String(request.getParameter("preciseProcessName"));
		try {
			preciseProcessName=java.net.URLDecoder.decode(preciseProcessName,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String title = request.getParameter("title");
		//title = ParamEscapeUtil.unescape(title);
		String startGroupName = ValidateUtils.filter(request.getParameter("startGroupName"));
		String startTimeBegin = ValidateUtils.filter(request.getParameter("startTimeBegin"));
		String startTimeEnd = ValidateUtils.filter(request.getParameter("startTimeEnd"));
		String receiveTimeBegin = ValidateUtils.filter(request.getParameter("receiveTimeBegin"));
		String receiveTimeEnd = ValidateUtils.filter(request.getParameter("receiveTimeEnd"));
        String createTimeBegin = ValidateUtils.filter(request.getParameter("createTimeBegin"));//接收时间
        String createTimeEnd = ValidateUtils.filter(request.getParameter("createTimeEnd"));
		String from = ValidateUtils.filter(request.getParameter("from"));
		String orderby = StringUtils.null2String(request.getParameter("orderby"));
		String order = StringUtils.null2String(request.getParameter("order"));
		String status = StringUtils.null2String(request.getParameter("status"));//流程状态  11-退回   12-转交

		String isDeal = StringUtils.null2String(request.getParameter("isDeal"));//0 待办  1 待处理
		//String module = request.getParameter("module");
		@SuppressWarnings("unused")
		String buttonGroup = request.getParameter("buttonGroup");
		//处理标题特殊字数
		/*String newTitle ="";
		if(StringUtils.isNotEmpty(title)){
			if (title.indexOf("&amp;")>-1) {
				newTitle = title.replaceAll("&amp;", "&");
				title = newTitle;
			}
		}*/
		if(!DocumentValidateUtil.validateParamsString(code,category,processName,preciseProcessName,startGroupName,startTimeBegin,startTimeEnd,receiveTimeBegin,receiveTimeEnd,createTimeBegin)) {
			return  new PageImpl(new ArrayList<Map>(),pageable,0);
		}
		if(!DocumentValidateUtil.validateParamsString(createTimeEnd,from,status,buttonGroup)) {
			return  new PageImpl(new ArrayList<Map>(),pageable,0);
		}
		if(buttonGroup!=null && buttonGroup.length()>0){
			buttonGroup = buttonGroup.replace(",goa_doc_sendfile","").replace("goa_doc_sendfile,","").replace("goa_doc_sendfile","");
			buttonGroup = buttonGroup.replace(",goa_doc_receivefile","").replace("goa_doc_receivefile,","").replace("goa_doc_receivefile","");
			buttonGroup = buttonGroup.replace(",goa_doc_signreport","").replace("goa_doc_signreport,","").replace("goa_doc_signreport","");
		}
		Map map = new HashMap();
		map.put("title", title);
		map.put("preciseProcessName", preciseProcessName);
		map.put("taskStatus", status);
		map.put("isDeal", isDeal);
		map.put("startTimeBegin", StringUtils.isNoneBlank(startTimeBegin) ? startTimeBegin+" 00:00:00" : "");//发起时间
		map.put("startTimeEnd", StringUtils.isNoneBlank(startTimeEnd) ? startTimeEnd+" 23:59:59" :"");
		map.put("receiveTimeBegin", StringUtils.isNoneBlank(receiveTimeBegin) ? receiveTimeBegin+" 00:00:00" : "");//办结时间
		map.put("receiveTimeEnd",  StringUtils.isNoneBlank(receiveTimeEnd)? receiveTimeEnd+" 23:59:59" : "");
		map.put("buttonGroup", StringUtils.null2String(buttonGroup));
		//map.put("buttonGroup", "button_group22");
		map.put("processName", StringUtils.null2String(processName));
        if (StringUtils.isNotBlank(createTimeBegin)) {
            map.put("createTimeBegin", createTimeBegin + " 00:00:00");
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd + " 23:59:59");
        }
		//是否涉密开启
        Boolean secretFlag = GlobalConstant.isUseSecretLevel();
        String secretLevel = "";
        if(secretFlag) {
        	//获取当前登录人的涉密登记
            secretLevel = String.valueOf(user.getSecretLevel());
            map.put("secretLevel", secretLevel);
        }
		if(StringUtils.isNotBlank(orderby)) {
            map.put("orderby", orderby);
		}
		if(StringUtils.isNotBlank(order)) {
            map.put("order", order);
		}
		if (StringUtils.isBlank(index)) {
			index = "0";
		}
		if (StringUtils.isBlank(limit)) {
			limit = "10";
		}
		if(StringUtils.isNotEmpty(startGroupName)){
			index = "0";
			limit = "10000";
		}else {
			map.put("startGroupName", startGroupName);
		}
		List<GovBaseSet> baseSetList = govCacheManager.getGovBaseInfoCache();
		if(baseSetList == null ) {
			baseSetList = govBaseSetService.findAll();
			govCacheManager.setGovBaseInfoCache(baseSetList);
		}
		GovBaseSet govBaseSet = new GovBaseSet();
		if (baseSetList != null && !baseSetList.isEmpty()){
			govBaseSet = baseSetList.get(0);
		}
		Map userParams = new HashMap();
		userParams.put("userId", user.getUserId());
		userParams.put("corpId", user.getCorpId());
		userParams.put("index", index);
		userParams.put("limit", limit);
		//userParams.put("code", "goa_document");
		userParams.put("code", StringUtils.null2String(code));
		userParams.put("category", category);
		userParams.put("module", "goa_document");
		userParams.put("from", "pendingList");
		userParams.put("groupId", user.getCurrentPtOrgId());
		if ((StringUtils.isNotBlank(title)) || (StringUtils.isNotBlank(startGroupName))
				|| (StringUtils.isNotBlank(startTimeBegin)) || (StringUtils.isNotBlank(startTimeEnd))  
				|| (StringUtils.isNotBlank(receiveTimeBegin)) || (StringUtils.isNotBlank(receiveTimeEnd))
				|| (StringUtils.isNotBlank(buttonGroup)) ||(StringUtils.isNotBlank(processName))||(StringUtils.isNotBlank(isDeal))
				|| StringUtils.isNotBlank(orderby) || StringUtils.isNotBlank(secretLevel) || StringUtils.isNotBlank(preciseProcessName)
				|| StringUtils.isNotBlank(status) || StringUtils.isNotBlank(createTimeBegin) || StringUtils.isNotBlank(createTimeEnd)) {
			userParams.put("searchData", JsonUtils.writeValueAsString(map));
		}
		logger.error("待处理页签userParams参数："+userParams);
		//使用接口调用。
		String json = bpmApiService.getUndoTaskList(userParams,user.getJwtToken());
		Map m = JsonUtils.readValue(json);
		Map data = (Map) m.get("data");
		List<Map> list = (List) data.get("list");
		int total = Integer.parseInt(data.get("count").toString());
		//处理发起单位
		for (int i = 0; i < list.size(); i++) {
			Long startTime2 = System.currentTimeMillis();
			((Map) list.get(i)).put("systemTime", new Date());
			//处理发起单位的数据
			if (((Map) list.get(i)).get("startUserId") != null) {
				List<Map> orgIdList = govFlowTaskService.getOrgIdByUser(((Map) list.get(i)).get("startUserId").toString());
				if (orgIdList !=null && !orgIdList.isEmpty()) {
					if (orgIdList.get(0).get("org_id") != null) {
						String orgShowName = baseSetService.getOrgShowName(orgIdList.get(0).get("org_id").toString());
						String startUserGroupNameFull = (String) ((Map) list.get(i)).get("startUserGroupNameFull");
						if (StringUtils.isNotBlank(startUserGroupNameFull)) {
							((Map) list.get(i)).put("startUserGroupName", orgShowName);
						}
					}
				}
			}
			Long endTime2 = System.currentTimeMillis();
			logger.info("发起单位时间："+(endTime2-startTime2));
		}
		if(StringUtils.isNotEmpty(startGroupName)){
			logger.error("==startGroupName不为空===="+startGroupName);
			if(CollectionUtils.isNotEmpty(list)){
				int startIndex = (Integer.parseInt(page)-1)*Integer.parseInt(rows);
				int endIndex =  Integer.parseInt(page)*Integer.parseInt(rows);
				list = list.stream().filter(lm->StringUtils.null2String(lm.get("startUserGroupName")).indexOf(startGroupName)>-1).collect(Collectors.toList());
				total = Integer.parseInt(String.valueOf(list.size()));
				if(endIndex<=total){
					list = list.subList(startIndex,endIndex);
				}else {
					list = list.subList(startIndex,total);
				}
			}
		}
		logger.error("---------公文待办list:"+JSONObject.toJSONString(list));
		Long endTime1 = System.currentTimeMillis();
		logger.info("待办接口获取时间："+(endTime1-startTime));
		List bussnessKeyList = new ArrayList();
		List processInstanceIdList = new ArrayList();
		List taskIdList = new ArrayList();
		if ((null != list) && (list.size() > 0)) {
			for (int n = 0; n < list.size(); n++) {
				String bussnessKey = (String) ((Map) list.get(n)).get("businessKey");
				String processInstanceId = (String) ((Map) list.get(n)).get("processInstanceId");
				String taskId = (String) ((Map) list.get(n)).get("id");
				bussnessKeyList.add(bussnessKey);
				processInstanceIdList.add(processInstanceId);
			}

			 //紧急程度,正式公文等字段判断
			 list  = govCommonService.setBussinessInfo(bussnessKeyList,list,"businessKey",govBaseSet);
			 if ( null != govBaseSet &&  StringUtils.isNotEmpty(govBaseSet.getListOperation()) && govBaseSet.getListOperation().indexOf("1") > -1){
				 //加入是否收藏
				 list  = govCommonService.setCollection(bussnessKeyList,list,user.getUserId(),"businessKey");
			 }
			 if ( null != govBaseSet &&  StringUtils.isNotEmpty(govBaseSet.getListOperation()) && govBaseSet.getListOperation().indexOf("3") > -1){
				 //判断是否有附件
				 list  = govCommonService.setAttach(bussnessKeyList,list,user.getUserId(),"businessKey");
				 list  = govCommonService.setSignApprove(processInstanceIdList,list,"processInstanceId");
			 }
			if ( null != govBaseSet &&  StringUtils.isNotEmpty(govBaseSet.getListOperation()) && govBaseSet.getListOperation().indexOf("2") > -1){
				//判断是否关注
				list  = govCommonService.setFollow(processInstanceIdList,list,user.getUserId(),"processInstanceId");
			}
		}
		Long endTime = System.currentTimeMillis();
		logger.info("待办列表时间："+(endTime-startTime));
		//return new PageImpl(list, pageable, total);
        list = DocumentSecUtils.approveListEncodeList(list,"id,processInstanceId","");
		return new PageImpl(list, pageable, total);
	}
	

	/**
	 * 已办列表
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map<String, Object> getDoneTaskList(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String index = ValidateUtils.filter(request.getParameter("start"));
		String limit = ValidateUtils.filter(request.getParameter("limit"));
		String code = ValidateUtils.filter(request.getParameter("code"));
		//String category = ValidateUtils.filter(request.getParameter("category"));
		String title = ValidateUtils.filter(request.getParameter("title"));
		title = ParamEscapeUtil.unescape(title);
		String from = ValidateUtils.filter(request.getParameter("from"));
		String module = ValidateUtils.filter(request.getParameter("module"));
		String startGroupName = ValidateUtils.filter(request.getParameter("startGroupName"));
		String startTimeBegin = ValidateUtils.filter(request.getParameter("startTimeBegin"));
		String startTimeEnd = ValidateUtils.filter(request.getParameter("startTimeEnd"));
		String dealTimeBegin = ValidateUtils.filter(request.getParameter("dealTimeBegin"));
		String dealTimeEnd = ValidateUtils.filter(request.getParameter("dealTimeEnd"));
		String category = ValidateUtils.filter(request.getParameter("categoryCode"));
		Map map = new HashMap();
		if(!DocumentValidateUtil.validateParamsString(code,from,module,startGroupName,startTimeBegin,startTimeEnd)) {
			map.put("list",Collections.emptyList());
			map.put("count",0);
			return  map;
		}
		if(!DocumentValidateUtil.validateParamsString(dealTimeBegin,dealTimeEnd,category)) {
			map.put("list",Collections.emptyList());
			map.put("count",0);
			return  map;
		}

		map.put("title", title);
		if(StringUtils.isNotEmpty(startGroupName)){
			index = "0";
			limit = "10000";
		}else {
			map.put("startGroupName", startGroupName);
		}
		map.put("startTimeBegin", StringUtils.isNoneBlank(startTimeBegin)? startTimeBegin+" 00:00:00" : "");//发起时间
		map.put("startTimeEnd", StringUtils.isNoneBlank(startTimeEnd) ? startTimeEnd+" 23:59:59" :"");
		map.put("dealTimeBegin",StringUtils.isNoneBlank(dealTimeBegin) ? dealTimeBegin+" 00:00:00" : "");//办结时间
		map.put("dealTimeEnd",  StringUtils.isNoneBlank(dealTimeEnd)? dealTimeEnd+" 23:59:59" : "");
		//是否涉密开启
        Boolean secretFlag = GlobalConstant.isUseSecretLevel();
        String secretLevel = "";
        if(secretFlag) {
        	//获取当前登录人的涉密登记
            secretLevel = String.valueOf(user.getSecretLevel());
            map.put("secretLevel", secretLevel);
        }
		if (StringUtils.isBlank(index)) {
			index = "0";
		}
		if (StringUtils.isBlank(limit)) {
			limit = "10";
		}
		Map userParams = new HashMap();
		userParams.put("userId", user.getUserId());
		userParams.put("corpId", user.getCorpId());
		userParams.put("index", index);
		userParams.put("limit", limit);
		userParams.put("code", StringUtils.null2String(code));
		userParams.put("category",category);
		userParams.put("module", module);
		userParams.put("from", from);
		userParams.put("groupId", user.getCurrentPtOrgId());
		if ((StringUtils.isNotBlank(title)) || (StringUtils.isNotBlank(startGroupName))
				|| (StringUtils.isNotBlank(startTimeBegin)) || (StringUtils.isNotBlank(startTimeEnd))
				|| (StringUtils.isNotBlank(dealTimeBegin)) || (StringUtils.isNotBlank(dealTimeEnd)) || (StringUtils.isNotBlank(category)) || (StringUtils.isNotBlank(secretLevel))) {
			userParams.put("searchData", JsonUtils.writeValueAsString(map));
		}
		String json = bpmApiService.getDoneProcessList(userParams,user.getJwtToken());
		Map m = JsonUtils.readValue(json);
		Map data = (Map) m.get("data");
		return data;
	}

	/**
	 * 
	 * @Description: 获取已办列表数据 
	 * @Title: GovFlowListWebApiController 
	 * @author: Fangsx
	 * @Date: 2019年12月26日 下午2:57:55 
	 * @param request
	 * @return
	 * @throws
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = { "/getDoneProcessList" }, method = {RequestMethod.GET })
	@ResponseBody
	public Page getDoneProcessList(HttpServletRequest request) {
		Long  startTime = System.currentTimeMillis();
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		WebUser user = WebUtils.getCurrentUser();
		Map data = getDoneTaskList(request);
		Long  endTime1 = System.currentTimeMillis();
		logger.info("已办办列表接口时间："+(endTime1-startTime));
		List<Map> list = (List) data.get("list");
		//发起单位的数据查询
		for (int i = 0; i < list.size(); i++) {
			((Map) list.get(i)).put("systemTime", new Date());
			//((Map) list.get(i)).put("moduleName", moduleMap.get((String) ((Map) list.get(i)).get("module")));
			if (((Map) list.get(i)).get("startUserGroupId") != null) {
				String orgShowName = baseSetService.getOrgShowName(((Map) list.get(i)).get("startUserGroupId").toString());
				if (StringUtils.isNotBlank(orgShowName)) {
					((Map) list.get(i)).put("startUserGroupName", orgShowName);
				}
			}
		}
		int total = Integer.parseInt(data.get("count").toString());
		String startGroupName = ValidateUtils.filter(request.getParameter("startGroupName"));
		String page = ValidateUtils.filter(request.getParameter("page"));
		String rows = ValidateUtils.filter(request.getParameter("rows"));
		if(StringUtils.isNotEmpty(startGroupName)){
			logger.error("==startGroupName不为空===="+startGroupName);
			if(CollectionUtils.isNotEmpty(list)){
				int startIndex = (Integer.parseInt(page)-1)*Integer.parseInt(rows);
				int endIndex =  Integer.parseInt(page)*Integer.parseInt(rows);
				list = list.stream().filter(lm->StringUtils.null2String(lm.get("startUserGroupName")).indexOf(startGroupName)>-1).collect(Collectors.toList());
				total = Integer.parseInt(String.valueOf(list.size()));
				if(endIndex<=total){
					list = list.subList(startIndex,endIndex);
				}else {
					list = list.subList(startIndex,total);
				}
			}
		}
		//String module = request.getParameter("module");
		//String category = ValidateUtils.filter(request.getParameter("category"));
		//Map moduleMap = this.govFlowTaskService.getAllModulesAndCode();
		List bussnessKeyList = new ArrayList();
		List processInstanceIdList = new ArrayList();
		List taskIdList = new ArrayList();
		List<GovBaseSet> baseSetList = govCacheManager.getGovBaseInfoCache();
		if(baseSetList == null ) {
			baseSetList = govBaseSetService.findAll();
			govCacheManager.setGovBaseInfoCache(baseSetList);
		}
		GovBaseSet govBaseSet = new GovBaseSet();
		if (baseSetList != null && !baseSetList.isEmpty()){
			govBaseSet = baseSetList.get(0);
		}
		if ((null != list) && (list.size() > 0)) {
			for (int n = 0; n < list.size(); n++) {
				String bussnessKey = (String) ((Map) list.get(n)).get("businessKey");
				String processInstanceId = (String) ((Map) list.get(n)).get("processInstanceId");
				String taskId = (String) ((Map) list.get(n)).get("taskId");
				bussnessKeyList.add(bussnessKey);
				processInstanceIdList.add(processInstanceId);
				taskIdList.add(taskId);
			}
			if (bussnessKeyList != null && !bussnessKeyList.isEmpty() ) {
				//紧急程度,正式公文等字段判断
				list  = govCommonService.setBussinessInfo(bussnessKeyList,list,"businessKey",govBaseSet);
				if ( null != govBaseSet &&  StringUtils.isNotEmpty(govBaseSet.getListOperation()) && govBaseSet.getListOperation().indexOf("1") > -1){
					//加入是否收藏
					list  = govCommonService.setCollection(bussnessKeyList,list,user.getUserId(),"businessKey");
				}
				if ( null != govBaseSet &&  StringUtils.isNotEmpty(govBaseSet.getListOperation()) && govBaseSet.getListOperation().indexOf("3") > -1){
					//判断是否有附件
					list  = govCommonService.setAttach(bussnessKeyList,list,user.getUserId(),"businessKey");
					list  = govCommonService.setSignApprove(processInstanceIdList,list,"processInstanceId");
				}
				if ( null != govBaseSet &&  StringUtils.isNotEmpty(govBaseSet.getListOperation()) && govBaseSet.getListOperation().indexOf("2") > -1){
					//判断是否关注
					list  = govCommonService.setFollow(processInstanceIdList,list,user.getUserId(),"processInstanceId");
				}
			}
			Long endTime = System.currentTimeMillis();
			logger.info("已办列表时间："+(endTime-startTime));
		}
        list = DocumentSecUtils.approveListEncodeList(list,"id,processInstanceId","");
		return new PageImpl(list, pageable, total);
	}
	
	
	 private Map<String,String> getFileStatus(String businessKey,String category,String distributeUserId,String fromWhere){
    	Map<String,String> map = new HashMap<String,String>();
    	String att = "";
    	String format_doc = "";
    	String filecontent = "";
    	if("goa_doc_signreport".equals(category)) {
    		DocSignreport findOne = signQueryService.findOne(businessKey);
    		if(findOne != null) {
    			att = this.getAllFileId(findOne.getAttachment(), findOne.getId(),fromWhere,distributeUserId);
        		if(findOne.getFileContent()!=null) {
        			filecontent = findOne.getFileContent();
        		}
        		if(findOne.getFormatFile()!=null) {
        			format_doc  =findOne.getFormatFile();
        		}
    		}
    	}else if("goa_doc_receivefile".equals(category)) {
    		GovDocReceiveFile findOne = govDocReceiveFileService.findOne(businessKey);
    		if(findOne != null) {
    			att = this.getAllFileId(findOne.getAttachment(), findOne.getId(),fromWhere,distributeUserId);
        		if(findOne.getFileContent()!=null) {
        			filecontent = findOne.getFileContent();
        		}
        		if(findOne.getFormatFile()!=null) {
        			format_doc  =findOne.getFormatFile();
        		}
    		}
    	}else {
    		GovSendFile findOne = sendFileService.findOne(businessKey);
    		if(findOne != null) {
    			att = this.getAllFileId(findOne.getAttachment(), findOne.getId(),fromWhere,distributeUserId);
        		if(findOne.getFileContent()!=null) {
        			filecontent = findOne.getFileContent();
        		}
        		if(findOne.getFormatFile()!=null) {
        			format_doc  =findOne.getFormatFile();
        		}
    		}
    	}
    	map.put("format_doc", format_doc);
    	map.put("filecontent", filecontent);
    	map.put("att", att);
    	return map;
    }
	 
	 
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String getAllFileId(String attachmentId, String id, String fromWhere, String distributeId) {
		String tempStrId = "";
		List<String> list = new ArrayList<String>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if("read".equals(fromWhere)) {//待阅传阅分发转发 
			GovDistributeUser govDistributeUser = govDistributeUserService.findOne(distributeId);
			String file = govDistributeUser.getDisContentEnclosure();		// 附件
			String fileIds = govDistributeUser.getFileRealIds();
			if("1".equals(file) && StringUtils.isNotEmpty(fileIds)) {
				/*List<String> temp = Arrays.asList(fileIds.split("\\|"));
				String sql = "select id from sys_attachment where file_name in (:ids)";
				paramMap.put("ids", temp);
				List<Map> tempList = downloadFilesService.findByListNativeQuery(sql, "", paramMap);
				if(tempList.size() >0 && tempList != null) {
					for (int i = 0;i < tempList.size(); i++) {
						Map map = tempList.get(i);
						Object tempId = map.get("id");
						if(tempId != null) {
							tempStrId = tempId.toString() + "|" + tempStrId;
						}
					}
				}*/
				GovDistributeRecord disRecord = govDistributeRecordService.findOne(govDistributeUser.getDisRecordId());
				if(disRecord!=null) {
					String source = disRecord.getSource();
					if(source.equals("3")||source.equals("4")) {
						List<String> attachmentList = new ArrayList<String>();
						String[] attachArr = fileIds.split("\\|");
						for(int i=0;i<attachArr.length;i++) {
							attachmentList.add(attachArr[i]);
						}
						List<GovDocAttachment> attachList = govDocAttachmentDao.getAttachmentListByRealIds(attachmentList);
						if(attachList!=null&&attachList.size()>0) {
							String newattachmentId = "";
							for(int i=0;i<attachList.size();i++) {
								GovDocAttachment attachOne = attachList.get(i);
								newattachmentId += attachOne.getSysAttchmentId()+"|";
							}
							if(!"".equals(newattachmentId)) {
								tempStrId = newattachmentId.substring(0, newattachmentId.length()-1);
							}
						}
					}else {
						List<String> temp = Arrays.asList(fileIds.split("\\|"));
						String sql = "select id from sys_attachment where file_name in (:ids)";
						paramMap.put("ids", temp);
						List<Map> tempList = downloadFilesService.findByListNativeQuery(sql, "", paramMap);
						if(tempList.size() >0 && tempList != null) {
							for (int i = 0;i < tempList.size(); i++) {
								Map map = tempList.get(i);
								Object tempId = map.get("id");
								if(tempId != null) {
									tempStrId = tempId.toString() + "|" + tempStrId;
								}
							}
						}
					}
				}
			}
		}else {
			String filePageAttachmentId = downloadFilesService.getFilePageUploadFile(id);
			if(StringUtils.isNotEmpty(attachmentId)) {
				if(StringUtils.isNotEmpty(filePageAttachmentId)) {
					attachmentId = attachmentId + "|"+filePageAttachmentId;
				}
			}else {
				attachmentId = filePageAttachmentId;
			}
			
			String[] array = attachmentId.split("\\|");
			if(array != null && array.length > 0) {
				for(int i=0;i<array.length;i++) {
					if(!list.contains(array[i])) {
						list.add(array[i]);
					}
				}
			}
			tempStrId = String.join("|", list);
		}
		return tempStrId;
	}
	/**
	 * 待办公文查看日志
	 * @param request
	 * @param title 标题
	 * @return
	 */
	@RequestMapping(value = "/addSeeLogDB")
	@ResponseBody
	public OperationResult addSeeLogDB(HttpServletRequest request) {
		String title = ValidateUtils.filter(StringUtils.null2String(request.getParameter("title")));
		title= title.replaceAll("&#43;", "+");
		String menuType = ValidateUtils.filter(StringUtils.null2String(request.getParameter("menutype")));
		/*if(!DocumentValidateUtil.validateTitle(title)) {
			throw new ValidationException("非法参数");
		}*/
		/*if(menuType.equals("done")){
			if(logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_DONE_03, TOKEN)) {
				logService.saveModuleLog(LogConstant.GOA_DOCUMENT_DONE_03, title, "");
			}
		}else */
		if(menuType.equals("start")){
			//if(logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_START_02, TOKEN)) {
			//	logService.saveModuleLog(LogConstant.GOA_DOCUMENT_START_02, "新建发文流程："+title+"，成功", "");
			//}
		}
		else if(menuType.equals("draft")){
			//if(logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_START_02, TOKEN)) {
			//	logService.saveModuleLog(LogConstant.GOA_DOCUMENT_START_02, "新建发文流程："+title+"，成功", "");
			//}
		}
		/*else if(menuType.equals("pending") && !title.equals("")){
			if(logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_PENDING_CK, TOKEN)) {
				logService.saveModuleLog(LogConstant.GOA_DOCUMENT_PENDING_CK, title, "");
			}
		}*/
		else if(menuType.equals("reduction") && !title.equals("")){
			if(logService.checkOptLog("0", "trashBox:log:05", TOKEN)) {
				logService.saveModuleLog("trashBox:log:05", title, "");
			}
		}

		return OperationResult.buildSuccessResult();
	}
	/**
	 * 待办公文呈领导日志
	 * @param request
	 * @param title 标题
	 * @return
	 */
	@RequestMapping(value = "/toLeaderLogDB")
	@ResponseBody
	public OperationResult toLeaderLogDB(HttpServletRequest request) {
		String title = ValidateUtils.filter(request.getParameter("title"));
		if (logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_PENDING_CLD, TOKEN)) {
			logService.saveModuleLog(LogConstant.GOA_DOCUMENT_PENDING_CLD, title, "");
		}
		return OperationResult.buildSuccessResult();
	}

	/**
	 * 待办公文呈领导日志
	 * @param request
	 * @param title 标题
	 * @return
	 */
	@RequestMapping(value = "/insertStartLog")
	@ResponseBody
	public OperationResult insertStartLog(HttpServletRequest request) {
		String title = ValidateUtils.filter(request.getParameter("title"));
		if (logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_START_02, TOKEN)) {
			logService.saveModuleLog(LogConstant.GOA_DOCUMENT_START_02, title, "");
		}
		return OperationResult.buildSuccessResult();
	}

	@RequestMapping(value = "/turnFileLog")
	@ResponseBody
	public OperationResult turnFileLog(HttpServletRequest request) {
		String title = ValidateUtils.filter(request.getParameter("title"));
		String type = ValidateUtils.filter(request.getParameter("type"));
		if("receivefile".equals(type)){
			if (logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_PENDING_ZSW, TOKEN)) {
				logService.saveModuleLog(LogConstant.GOA_DOCUMENT_PENDING_ZSW, title, "");
			}
		}else if("sendfile".equals(type)){
			if (logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_PENDING_ZFW, TOKEN)) {
				logService.saveModuleLog(LogConstant.GOA_DOCUMENT_PENDING_ZFW, title, "");
			}
		}else if("signreport".equals(type)){
			if (logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_PENDING_ZQB, TOKEN)) {
				logService.saveModuleLog(LogConstant.GOA_DOCUMENT_PENDING_ZQB, title, "");
			}
		}
		return OperationResult.buildSuccessResult();
	}


	/**
	  * 待办公文数量
	 * @param request
	 * @param status 流程状态
	 * @param isClaim 1签收 0未签收
	 * @return
	 */
	@RequestMapping(value = "/getUndoNum",method = RequestMethod.GET)
	@ResponseBody
	public OperationResult getUndoNum(HttpServletRequest request) {
		WebUser user  = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		String status = StringUtils.null2String(request.getParameter("status"));//流程状态  11-退回   12-转交
		String isClaim = StringUtils.null2String(request.getParameter("isClaim"));//1签收 0未签收

		if(!DocumentValidateUtil.validateParamsString(status,isClaim)) {
			throw new ValidationException("非法参数");
		}
		Map<String,String>   paramMap = new HashMap<String,String>();
		paramMap.put("userId", userId);
		paramMap.put("corpId", corpId);
		paramMap.put("module", "goa_document");
		Map map = new HashMap();
		//是否涉密开启
        Boolean secretFlag = GlobalConstant.isUseSecretLevel();
		map.put("taskStatus", status);
		if (StringUtils.isNotEmpty(isClaim)){
			map.put("isClaim", isClaim);
		}
        String secretLevel = "";
        if(secretFlag) {
        	//获取当前登录人的涉密登记
            secretLevel = String.valueOf(user.getSecretLevel());
            map.put("secretLevel", secretLevel);
        }
        paramMap.put("searchData", JsonUtils.writeValueAsString(map));
		String json = bpmApiService.getUndoTaskCount(paramMap,user.getJwtToken());
		Map m = JsonUtils.readValue(json);
		String  resultNum =  (String) m.get("data");
		return OperationResult.buildSuccessResult("成功", resultNum);
	}

	/**
	  * 草稿箱数量
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getDraftNum",method = RequestMethod.GET)
	@ResponseBody
	public OperationResult getDraftNum(HttpServletRequest request) {
		WebUser user  = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		String  resultNum =  sendFileService.getDraftNum(userId,corpId,"goa_document");
		return OperationResult.buildSuccessResult("成功", resultNum);
	} 
	
	
	/**
	  * 已办公文数量
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getDoneNum")
	@ResponseBody
	public OperationResult getDoneNum(HttpServletRequest request) {
		WebUser user  = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		String  resultNum =  sendFileService.getDoneNum(userId,corpId,"goa_document");
		return OperationResult.buildSuccessResult("成功", resultNum);
	} 
	
	
	/**
	  * 我的发起公文数量
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getMyStartNum")
	@ResponseBody
	public OperationResult getMyStartNum(HttpServletRequest request) {
		WebUser user  = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		String  resultNum =  sendFileService.getMyStartNum(userId,corpId,"goa_document");
		return OperationResult.buildSuccessResult("成功", resultNum);
	} 
	
	/**
	 * 获取批示意见
	 * @name: getComListByProTaskType
	 * @param request
	 * @param processInstanceId 流程实例id
	 * @param taskId 任务id
	 * @param commentType 意见类型
	 * @return: org.ezplatform.core.web.view.OperationResult
	 * @date: 2022/10/18 14:24
	 *
	*/
	@RequestMapping(value = "/getComListByProTaskType")
	@ResponseBody
	public OperationResult getComListByProTaskType(HttpServletRequest request,String processInstanceId,String taskId,String commentType) {
		WebUser user  = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		if(!DocumentValidateUtil.validateParamsString(processInstanceId,taskId,commentType)) {
			throw new ValidationException("非法参数");
		}
		List<Map> comListByProTaskType = sendFileService.getComListByProTaskType(processInstanceId, taskId, commentType, userId);
	    if (comListByProTaskType != null && !comListByProTaskType.isEmpty()) {
			return OperationResult.buildSuccessResult("成功",comListByProTaskType);
		}
	    return OperationResult.buildFailureResult("获取失败");
	}

	/**
	 * 获取附件信息
	 * @param request
	 * @param id 附件id
	 * @return
	 */
	@RequestMapping(value = "/getAttachmentByIds")
	@ResponseBody
	public OperationResult getAttachmentByIds(HttpServletRequest request,String id) {
		if (StringUtils.isNotEmpty(id)){
			WebUser user  = WebUtils.getCurrentUser();
			String userId = user.getUserId();
			String corpId = user.getCorpId();
			if(!DocumentValidateUtil.validateParamsString(id)) {
				throw new ValidationException("非法参数");
			}
			List<Map<String, String>> attachmentFileList = downloadFilesService.getAttachmentByIds(id,corpId,user.getJwtToken());
			if (attachmentFileList != null && !attachmentFileList.isEmpty()) {
				return OperationResult.buildSuccessResult("成功",attachmentFileList);
			}
		}
		return OperationResult.buildFailureResult("获取失败");
	}


	/**
	 * 保存批示意见
	 * @name: saveCommentList
	 * @param request
	 * @param data 批示意见数据
	 * @param module 模块编码
	 * @param processInstanceId 流程实例id
	 * @param taskId 任务id
	 * @return: org.ezplatform.core.web.view.OperationResult
	 * @date: 2022/10/18 14:25
	 *
	*/
	@RequestMapping(value = "/saveCommentList",method = RequestMethod.POST)
	@ResponseBody
	public OperationResult saveCommentList(HttpServletRequest request,String data,String module,String processInstanceId,String taskId) {
		WebUser user  = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		if(!DocumentValidateUtil.validateParamsString(module,processInstanceId,taskId)) {
			throw new ValidationException("非法参数");
		}

		if (!DocumentValidateUtil.validateParamsLength(taskId,-1,100)) {
			throw new ValidationException("非法参数");
		}
		Map<String,String> map = new HashMap<>();
		map.put("module",module);
		map.put("processInstanceId",processInstanceId);
		map.put("taskId",taskId);
		map.put("userId",userId);
		map.put("corpId",corpId);
		map.put("groupId",user.getGroupIds());
		data = data.replace("\\\"comment\\\":\\\"null\\\"", "\\\"comment\\\":\\\"\\\"");
		if (StringUtils.isNotEmpty(data)){
			String result = bpmApiService.saveCommentList(map,data,user.getJwtToken());
			Map<String, Object> readValue = JsonUtils.readValue(result);
			return OperationResult.buildSuccessResult("保存成功",readValue.get("data"));
		}
		return OperationResult.buildFailureResult("保存成功");
	}


	//下面是领导转办二开-------------------------------------------------------------------
	//20240726gaoyw秘书自定义转交获取领导待办列表-s
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = { "/myPendingTaskList" }, method = { RequestMethod.GET })
	@ResponseBody
	public Page myPendingTaskList(HttpServletRequest request) throws Exception {
		Long startTime = System.currentTimeMillis();
		WebUser user = WebUtils.getCurrentUser();

		String leaderId = myTransferFlowLeaderId(user.getUserId());//通过当前秘书得id获取领导的id
		String leaderOrgId = myTransferFlowLeaderOrgId(user.getUserId());//通过当前秘书得id获取领导的leaderOrgId
		String leaderLoginName = myTransferFlowLeaderLoginName(user.getUserId());//通过当前秘书得id获取领导的登录名
		String token = ssoAuth2(leaderLoginName);

		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		String index = ValidateUtils.filter(request.getParameter("start"));
		String limit = ValidateUtils.filter(request.getParameter("limit"));
		String code = ValidateUtils.filter(request.getParameter("code"));
		String category = ValidateUtils.filter(request.getParameter("categoryCode"));
		String processName = ValidateUtils.filter(request.getParameter("processName"));
		String preciseProcessName = StringUtils.null2String(request.getParameter("preciseProcessName"));
		try {
			preciseProcessName=java.net.URLDecoder.decode(preciseProcessName,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String title = ValidateUtils.filter(request.getParameter("title"));
		title = ParamEscapeUtil.unescape(title);
		String startGroupName = ValidateUtils.filter(request.getParameter("startGroupName"));
		String startTimeBegin = ValidateUtils.filter(request.getParameter("startTimeBegin"));
		String startTimeEnd = ValidateUtils.filter(request.getParameter("startTimeEnd"));
		String receiveTimeBegin = ValidateUtils.filter(request.getParameter("receiveTimeBegin"));
		String receiveTimeEnd = ValidateUtils.filter(request.getParameter("receiveTimeEnd"));
		String createTimeBegin = ValidateUtils.filter(request.getParameter("createTimeBegin"));//接收时间
		String createTimeEnd = ValidateUtils.filter(request.getParameter("createTimeEnd"));
		String from = ValidateUtils.filter(request.getParameter("from"));
		String orderby = StringUtils.null2String(request.getParameter("orderby"));
		String order = StringUtils.null2String(request.getParameter("order"));
		String status = StringUtils.null2String(request.getParameter("status"));//流程状态  11-退回   12-转交

		String isDeal = StringUtils.null2String(request.getParameter("isDeal"));//0 待办  1 待处理
		//String module = request.getParameter("module");
		@SuppressWarnings("unused")
		String buttonGroup = request.getParameter("buttonGroup");
		//处理标题特殊字数
		String newTitle ="";
		if(StringUtils.isNotEmpty(title)){
			if (title.indexOf("&amp;")>-1) {
				newTitle = title.replaceAll("&amp;", "&");
				title = newTitle;
			}
		}
		if(!DocumentValidateUtil.validateParamsString(code,category,processName,preciseProcessName,startGroupName,startTimeBegin,startTimeEnd,receiveTimeBegin,receiveTimeEnd,createTimeBegin)) {
			throw new ValidationException("非法参数");
		}
		if(!DocumentValidateUtil.validateParamsString(createTimeEnd,from,status,buttonGroup)) {
			throw new ValidationException("非法参数");
		}
		if(buttonGroup!=null && buttonGroup.length()>0){
			buttonGroup = buttonGroup.replace(",goa_doc_sendfile","").replace("goa_doc_sendfile,","").replace("goa_doc_sendfile","");
			buttonGroup = buttonGroup.replace(",goa_doc_receivefile","").replace("goa_doc_receivefile,","").replace("goa_doc_receivefile","");
			buttonGroup = buttonGroup.replace(",goa_doc_signreport","").replace("goa_doc_signreport,","").replace("goa_doc_signreport","");
		}
		Map map = new HashMap();
		map.put("title", title);
		map.put("startGroupName", startGroupName);
		map.put("preciseProcessName", preciseProcessName);
		map.put("taskStatus", status);
		map.put("isDeal", isDeal);
		map.put("startTimeBegin", StringUtils.isNoneBlank(startTimeBegin) ? startTimeBegin+" 00:00:00" : "");//发起时间
		map.put("startTimeEnd", StringUtils.isNoneBlank(startTimeEnd) ? startTimeEnd+" 23:59:59" :"");
		map.put("receiveTimeBegin", StringUtils.isNoneBlank(receiveTimeBegin) ? receiveTimeBegin+" 00:00:00" : "");//办结时间
		map.put("receiveTimeEnd",  StringUtils.isNoneBlank(receiveTimeEnd)? receiveTimeEnd+" 23:59:59" : "");
		map.put("buttonGroup", StringUtils.null2String(buttonGroup));
		//map.put("buttonGroup", "button_group22");
		map.put("processName", StringUtils.null2String(processName));
		if (StringUtils.isNotBlank(createTimeBegin)) {
			map.put("createTimeBegin", createTimeBegin + " 00:00:00");
		}
		if (StringUtils.isNotBlank(createTimeEnd)) {
			map.put("createTimeEnd", createTimeEnd + " 23:59:59");
		}
		//是否涉密开启
		Boolean secretFlag = GlobalConstant.isUseSecretLevel();
		String secretLevel = "";
//        if(secretFlag) {
//            //获取当前登录人的涉密登记
//            secretLevel = String.valueOf(user.getSecretLevel());
//            map.put("secretLevel", secretLevel);
//        }
		if(StringUtils.isNotBlank(orderby)) {
			map.put("orderby", orderby);
		}
		if(StringUtils.isNotBlank(order)) {
			map.put("order", order);
		}
		if (StringUtils.isBlank(index)) {
			index = "0";
		}
		if (StringUtils.isBlank(limit)) {
			limit = "10";
		}
		List<GovBaseSet> baseSetList = govCacheManager.getGovBaseInfoCache();
		if(baseSetList == null ) {
			baseSetList = govBaseSetService.findAll();
			govCacheManager.setGovBaseInfoCache(baseSetList);
		}
		GovBaseSet govBaseSet = new GovBaseSet();
		if (baseSetList != null && !baseSetList.isEmpty()){
			govBaseSet = baseSetList.get(0);
		}
		Map userParams = new HashMap();
		userParams.put("userId", leaderId);
		userParams.put("corpId", "0");
		userParams.put("index", index);
		userParams.put("limit", limit);
		//userParams.put("code", "goa_document");
		userParams.put("code", StringUtils.null2String(code));
		userParams.put("category", category);
		userParams.put("module", "goa_document");
		userParams.put("from", from);
		userParams.put("groupId", leaderOrgId);
		if ((StringUtils.isNotBlank(title)) || (StringUtils.isNotBlank(startGroupName))
				|| (StringUtils.isNotBlank(startTimeBegin)) || (StringUtils.isNotBlank(startTimeEnd))
				|| (StringUtils.isNotBlank(receiveTimeBegin)) || (StringUtils.isNotBlank(receiveTimeEnd))
				|| (StringUtils.isNotBlank(buttonGroup)) ||(StringUtils.isNotBlank(processName))||(StringUtils.isNotBlank(isDeal))
				|| StringUtils.isNotBlank(orderby) || StringUtils.isNotBlank(secretLevel) || StringUtils.isNotBlank(preciseProcessName)|| StringUtils.isNotBlank(status) || StringUtils.isNotBlank(createTimeBegin) || StringUtils.isNotBlank(createTimeEnd)) {
			userParams.put("searchData", JsonUtils.writeValueAsString(map));
		}
		logger.info("待处理页签userParams+++isDeal："+userParams.get("searchData"));
		logger.info("待处理页签map+++isDeal："+map.get("isDeal"));
		//使用接口调用。
		String json = bpmApiService.getUndoTaskList(userParams,token);
		Map m = JsonUtils.readValue(json);
		Map data = (Map) m.get("data");
		List list = (List) data.get("list");
		logger.info("---------list:"+list.toString());
		Long endTime1 = System.currentTimeMillis();
		logger.info("待办接口获取时间："+(endTime1-startTime));
		Map moduleMap = this.govFlowTaskService.getAllModulesAndCode();
		List bussnessKeyList = new ArrayList();
		List processInstanceIdList = new ArrayList();
		List taskIdList = new ArrayList();
		if ((null != list) && (list.size() > 0)) {
			for (int n = 0; n < list.size(); n++) {
				String bussnessKey = (String) ((Map) list.get(n)).get("businessKey");
				String processInstanceId = (String) ((Map) list.get(n)).get("processInstanceId");
				String taskId = (String) ((Map) list.get(n)).get("id");
				bussnessKeyList.add(bussnessKey);
				processInstanceIdList.add(processInstanceId);
				taskIdList.add(taskId);
			}
			for (int i = 0; i < list.size(); i++) {
				String moduleCode = (String) ((Map) list.get(i)).get("module");
				if (StringUtils.isNotBlank(moduleCode)) {
					((Map) list.get(i)).put("moduleName", moduleMap.get(moduleCode));
				}
				String bussnessKey = (String) ((Map) list.get(i)).get("businessKey");
				if (StringUtils.isNotBlank(bussnessKey)) {
					List<String> lists =new ArrayList<String>();
					lists.add(bussnessKey);
				}
				((Map) list.get(i)).put("systemTime", new Date());
				//处理发起单位的数据
				if (((Map) list.get(i)).get("startUserId") != null) {
					List<Map> orgIdList = govFlowTaskService.getOrgIdByUser(((Map) list.get(i)).get("startUserId").toString());
					if (orgIdList !=null && !orgIdList.isEmpty()) {
						if (orgIdList.get(0).get("org_id") != null) {
							String orgShowName = baseSetService.getOrgShowName(orgIdList.get(0).get("org_id").toString());
							String startUserGroupNameFull = (String) ((Map) list.get(i)).get("startUserGroupNameFull");
							if (StringUtils.isNotBlank(startUserGroupNameFull)) {
								((Map) list.get(i)).put("startUserGroupName", orgShowName);
							}
						}
					}
				}
			}

			//紧急程度,正式公文等字段判断
			list  = govCommonService.setBussinessInfo(bussnessKeyList,list,"businessKey",govBaseSet);

			if ( null != govBaseSet &&  StringUtils.isNotEmpty(govBaseSet.getListOperation()) && govBaseSet.getListOperation().indexOf("1") > -1){
				//加入是否收藏
				list  = govCommonService.setCollection(bussnessKeyList,list,leaderId,"businessKey");
			}

			if ( null != govBaseSet &&  StringUtils.isNotEmpty(govBaseSet.getListOperation()) && govBaseSet.getListOperation().indexOf("3") > -1){
				//判断是否有附件
				list  = govCommonService.setAttach(bussnessKeyList,list,leaderId,"businessKey");
				list  = govCommonService.setSignApprove(processInstanceIdList,list,"processInstanceId");
			}
			if ( null != govBaseSet &&  StringUtils.isNotEmpty(govBaseSet.getListOperation()) && govBaseSet.getListOperation().indexOf("2") > -1){
				//判断是否关注
				list  = govCommonService.setFollow(processInstanceIdList,list,leaderId,"processInstanceId");
			}
		}
		Long endTime = System.currentTimeMillis();
		logger.info("待办列表时间："+(endTime-startTime));
		//return new PageImpl(list, pageable, total);
		list = DocumentSecUtils.approveListEncodeList(list,"id,processInstanceId","");
		return new PageImpl(list, pageable, Long.valueOf(data.get("count").toString()).longValue());
	}


	//根据呗转交人得id获取被转角人得id
	public String myTransferFlowLeaderId(String userId) {
		String sql = "SELECT scopevalue leader_id ,name leader_name,su.login_name FROM ldgx_scope LEFT  JOIN sys_user su ON su.id=scopevalue WHERE \"fielddatavalue\"=(SELECT f1 FROM ldgx WHERE f2 in(SELECT fielddatavalue FROM ldgx_scope WHERE \"scopevalue\"=?)) ";
		List<Map<String, Object>> rlist=jdbcTemplate.queryForList(sql,new Object[]{userId});
		String leader_id ="";
		if(rlist.size()>0){
			for(int a=0;a<rlist.size();a++) {
				Map amap = (Map) rlist.get(a);
				leader_id = amap.get("leader_id") + "";
			}
		}
		System.out.println("====JiangChao====leader_id: " + leader_id);
		return leader_id;
	}
	//根据呗转交人得id获取被转角人得登录名
	public String myTransferFlowLeaderLoginName(String userId) {
		String sql = "SELECT scopevalue leader_id ,name leader_name,su.login_name FROM ldgx_scope LEFT  JOIN sys_user su ON su.id=scopevalue WHERE \"fielddatavalue\"=(SELECT f1 FROM ldgx WHERE f2 in(SELECT fielddatavalue FROM ldgx_scope WHERE \"scopevalue\"=?)) ";
		List<Map<String, Object>> rlist=jdbcTemplate.queryForList(sql,new Object[]{userId});
		String login_name ="";
		if(rlist.size()>0){
			for(int a=0;a<rlist.size();a++) {
				Map amap = (Map) rlist.get(a);
				login_name = amap.get("login_name") + "";
			}
		}
		System.out.println("====JiangChao====login_name: " + login_name);
		return login_name;
	}
	//根据呗转交人得id获取被转角人得orgid
	public String myTransferFlowLeaderOrgId(String userId) {
		String sql = "SELECT scopevalue leader_id ,name leader_name,su.login_name,su.org_id FROM ldgx_scope LEFT  JOIN sys_user su ON su.id=scopevalue WHERE \"fielddatavalue\"=(SELECT f1 FROM ldgx WHERE f2 in(SELECT fielddatavalue FROM ldgx_scope WHERE \"scopevalue\"=?)) ";
		List<Map<String, Object>> rlist=jdbcTemplate.queryForList(sql,new Object[]{userId});
		String org_id ="";
		if(rlist.size()>0){
			for(int a=0;a<rlist.size();a++) {
				Map amap = (Map) rlist.get(a);
				org_id = amap.get("org_id") + "";
			}
		}
		System.out.println("====JiangChao====org_id: " + org_id);
		return org_id;
	}

	//获取临时token
	public static AccessToken getAccess_token()  throws Exception {
		String url="http://172.24.240.126:18088/flexbase/oauth2/token";
		Client client = new Client();
		String client_secret="CwSgxC3alRiODHUTeAxC";//
		String client_id="OwlcVZp96gbfQnjyOGH0";//
		Map<String, String> params = new HashMap<String, String>();
		params.put("client_id", client_id);
		params.put("client_secret", client_secret);
		params.put("grant_type", "client_credentials");
		AccessToken acctessToken = client.getToken(url, params);
		System.out.println("====JiangChao====acctessToken: " + acctessToken.getAccessToken());
		return acctessToken;
	}

	//获取用户token
	public static  String   ssoAuth2(String leaderLoginName)  throws Exception {
		String url="http://172.24.240.126:18088/flexbase/api/system/logon/ssoAuth2";
		Client client = new Client();
		String token="";
		Map<String, String> params = new HashMap<String, String>();
		AccessToken acctessToken=getAccess_token();
		params.put("token ", acctessToken.getAccessToken());
		params.put("corpId", "0");
		params.put("loginType", "1");
		params.put("uid", leaderLoginName);
		String json = client.post(url, params, "", acctessToken);
		Map result = JsonUtils.readValue(json);
		if (result.get("type").toString().equals("success")) {
			Map data = (Map)result.get("data");
			token = StringUtils.null2String(data.get("token"));
			System.out.println("====JiangChao====token: " + token);
		}
		return token;
	}
//20240726gaoyw秘书自定义转交获取领导待办列表-e
}
